package com.baizhi.controller;

import cn.hutool.captcha.ICaptcha;
import com.baizhi.dao.AdminDao;
import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import com.baizhi.serviceplus.AdminServicePlus;
import com.baizhi.serviceplus.impl.AdminServicePlusImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.Map;

@Controller

public class AdminController {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private AdminService adminService;
   @Autowired
    private AdminServicePlus adminServicePlus;

    @RequestMapping("/login")
    public  String login(String username, String password, String code, HttpSession session) {
        //获取生成的验证码
        ICaptcha o = (ICaptcha) session.getAttribute("code");
        //获取生成的验证码
        String code1 = o.getCode();
        //判断验证码是否正确
        boolean c = o.verify(code1);

        //先拿到令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //获取主题
        Subject subject = SecurityUtils.getSubject();


        if (c) {
            try {
                subject.login(token);

                session.setAttribute("admin", adminDao.selectByName(username));

                return "redirect:/index.jsp";

            } catch (AuthenticationException e) {
                e.printStackTrace();

            }

        }
        return "login";

    }



    @RequestMapping("/selectAllAdmin")
    @ResponseBody
    public Map selectAllAdmin(Integer page,Integer limit ){
        Map map = adminService.selectAllAdmin(page,limit);
        return  map;
    }

    @RequestMapping("/insertAdmin")
    @ResponseBody
    public Map insert(Admin admin){
        Map map = adminServicePlus.insertAdmin(admin);
        return  map;
    }
    @RequestMapping("/updateAdmin")
    @ResponseBody
    public Map updateAdmin(Admin admin){
        Map map = adminServicePlus.updateAdmin(admin);
        return  map;
    }
    @RequestMapping("/deleteAdmin")
    @ResponseBody
    public Map deleteAdmin(Integer admin){
        Map map = adminServicePlus.deleteAdmin(admin);
        return  map;
    }


}
